package com.quan.commons.context;

import cn.hutool.core.util.BooleanUtil;
import com.quan.commons.utils.StopWatch;
import io.netty.util.concurrent.FastThreadLocal;

/**
 * 秒表容器
 */
public class StopWatchHolder {

    /**
     * 启用开关容器
     */
    private static final FastThreadLocal<Boolean> SWITCH_FLAG = new FastThreadLocal<>();

    /**
     * 当前秒表容器
     */
    private static final FastThreadLocal<StopWatch> CURRENT_STOP_WATCH = new FastThreadLocal<>();

    private static final String DEFAULT_TIP = "未开启秒表";

    /**
     * 容器组初始化(指定秒表名称)
     *
     * @param stopWatchName 秒表名称
     */
    public static void init(String stopWatchName) {
        Boolean switchFlag = SWITCH_FLAG.get();
        if (!BooleanUtil.isTrue(switchFlag)) {
            SWITCH_FLAG.set(true);
            StopWatch stopWatch = new StopWatch(stopWatchName);
            CURRENT_STOP_WATCH.set(stopWatch);
        }
    }

    /**
     * 容器组初始化
     */
    public static void init() {
        Boolean switchFlag = SWITCH_FLAG.get();
        if (!BooleanUtil.isTrue(switchFlag)) {
            SWITCH_FLAG.set(true);
            StopWatch stopWatch = new StopWatch();
            CURRENT_STOP_WATCH.set(stopWatch);
        }
    }

    /**
     * 指定秒表名称
     *
     * @param name 秒表名称
     */
    public static void setName(String name) {
        Boolean switchFlag = SWITCH_FLAG.get();
        if (BooleanUtil.isTrue(switchFlag)) {
            CURRENT_STOP_WATCH.get().setStopWatchName(name);
        }
    }

    /**
     * 开始一个任务
     *
     * @param taskName 任务名称
     */
    public static void start(String taskName) {
        Boolean switchFlag = SWITCH_FLAG.get();
        if (BooleanUtil.isTrue(switchFlag)) {
            CURRENT_STOP_WATCH.get().start(taskName);
        }
    }

    /**
     * 结束一个任务
     *
     * @param taskName 任务名称
     */
    public static void stop(String taskName) {
        Boolean switchFlag = SWITCH_FLAG.get();
        if (BooleanUtil.isTrue(switchFlag)) {
            CURRENT_STOP_WATCH.get().stop(taskName);
        }
    }

    /**
     * 美化打印结果
     *
     * @return java.lang.String
     */
    public static String prettyPrint() {
        Boolean switchFlag = SWITCH_FLAG.get();
        if (BooleanUtil.isTrue(switchFlag)) {
            return CURRENT_STOP_WATCH.get().prettyPrint();
        } else {
            return DEFAULT_TIP;
        }
    }

    /**
     * 删除保存的秒表
     */
    public static void remove() {
        SWITCH_FLAG.remove();
        CURRENT_STOP_WATCH.remove();
    }
}
